#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from k8s.env import TEMPLATES_DIR, CONF_DIR, IMAGE_REPO
from conf.jinja2_tool import jinja2_dump
from kubernetes import client, config
from conf.yaml_tool import yaml_load, yaml_dump
from log.logger import logger
from misc.color import INFO, SINFO, CRIT, SUMM, WARN
import commands

class DaemonsetClient(object):
    def __init__(self, namespace):
        from log.logger import logger
        self.logger = logger
        self.namespace = namespace
        self.ctx = client.AppsV1Api()

    def create(self, component):
        msg = "Namespace [%s]: creating Daemonset [%s]" % (self.namespace, component)
        self.logger.info(msg)
        print(SINFO % ("|--Info: " + msg))

        yaml_file = os.path.join(CONF_DIR, "%s/%s/ds.yaml" % (self.namespace, component))

        if os.path.getsize(yaml_file) == 0:
            msg = "skip empty file %s" % yaml_file
            self.logger.error(msg)
            print(WARN % ("  |--Warn: " + msg))
            return

        body = yaml_load(yaml_file)
        if not body:
            msg = "failed to load content from %s" % yaml_file
            self.logger.error(msg)
            print(CRIT % ("  |--Error: " + msg))
            return

        try:
            resp = self.ctx.create_namespaced_daemon_set(body=body, namespace=self.namespace)
            msg = "Namespace [%s]: Daemonset created. name='%s'" % (self.namespace, resp.metadata.name)
            self.logger.info(msg)
            print(INFO % ("  |--Info: " + msg))
        except Exception as e:
            # conflict exception: 409
            if str(e).split()[0] != '(409)':
                msg = str(e)
                print(CRIT % ("  |--Error: " + msg))
            else:
                msg = "instance already exits."
                print(INFO % ("  |--Info: " + msg))
            self.logger.critical(msg)

    def delete(self, name):
        try:
            resp = self.ctx.delete_namespaced_daemon_set(name=name, namespace=self.namespace)
            print("Daemonset deleted. name='%s'" % resp.metadata.name)
        except Exception as e:
            print(e)

    def update(self, component):
        yaml_file = os.path.join(CONF_DIR, "%s/%s/ds.yaml" % (self.namespace, component))
        msg = "Namespace [%s]: updating Daemonset [%s]" % (self.namespace, component)
        self.logger.info(msg)
        print(SINFO % ("|--Info: " + msg))

        status, msg = commands.getstatusoutput("export KUBECONFIG=/root/.kube/config; kubectl -n %s apply -f %s" % (self.namespace, yaml_file))
        if status == 0:
            self.logger.info(msg)
            print(INFO % ("  |--Info: " + msg))
        else:
            self.logger.error(msg)
            print(CRIT % ("  |--Error: " + msg))

    def patch(self, name, body):
        try:
            self.ctx.patchnam
            resp = self.ctx.patch_namespaced_daemon_set(name=name, namespace=self.namespace, body=body)
            msg = "Namespace [%s]: Daemonset patched. name='%s'" % (self.namespace, resp.metadata.name)
            self.logger.info(msg)
            print(INFO % ("  |--Info: " + msg))
        except Exception as e:
            print(e)

    def get(self, name):
        return self.ctx.read_namespaced_daemon_set(name=name, namespace=self.namespace)
